package models.my;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import models.user.UserInfo;

import play.Logger;
import play.db.ebean.Model;
import utils.MengException;
import utils.StringUtils;

/**
 * 用户积分消费记录
 * @author zhangpeng
 *
 */
@Entity
@Table(name="user_score_record")
public class MyScoreRecord extends Model{

	private static final long serialVersionUID = 1L;
	
	@Id
	public long id;
	public String username;
	/**
	 * 积分消费交易号
	 */
	public String trans_no = StringUtils.getTransNo();
	/**
	 * 操作 	 		
	 */
	public String operation;
	/**
	 * 积分变更
	 */
	public String change_score;
	/**
	 * 详情 
	 */
	public String detail;
	/**
	 * 变更时间
	 */
	public long change_time = StringUtils.getTimeStamp();
	
	public static MyScoreRecord getInstances(){
		return new MyScoreRecord();
	}
	
	public static Model.Finder<Long, MyScoreRecord> find = new Model.Finder<Long, MyScoreRecord>(Long.class, MyScoreRecord.class);
	
	/**
	 * 创建积分消费记录
	 * @param msr
	 * @return
	 */
	public boolean createMyScoreRecord(MyScoreRecord msr) throws MengException {
		
		if (UserInfo.getInstances().verifyUsername(msr.username)) {
			throw new MengException("120001", "用户名不存在");
		}

		try {
			msr.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createMyScoreRecord Exception," + t.getMessage());
			throw new MengException("120002", "创建积分消费记录失败");
		}
	}
	
	/**
	 * 获取积分消费记录历史列表
	 * @param page
	 * @param size
	 * @return
	 */
	public List<MyScoreRecord> getMyScoreRecord(String username, int page, int size) throws MengException{
		try {
			return find.where().eq("username", username).orderBy().desc("change_time").findPagingList(size).setFetchAhead(false).getPage(size).getList();
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo getMyScoreRecord Exception," + t.getMessage());
			throw new MengException("120005", "获取积分消费记录历史列表失败");
		}
	}

	
}
